package com.ijunfu.safe._01_Synchronized;

import lombok.extern.slf4j.Slf4j;

import java.util.stream.IntStream;

/**
 *
 * @Title  : 两个线程顺序打印
 * @Author : ijunfu <ijunfu@163.com>
 * @Date   : 2023/11/16 17:18
 * @Version: 1.0
 * @Motto  : 世界很大 世界很小
 *
 */
@Slf4j
public class SynchronizedTest {

    public static Integer num = 10;
    public static Boolean flag = Boolean.TRUE;

    public static Object lock = new Object();

    public static void main(String[] args) {

        Thread t1 = new Thread(()->{
            while(true) {
                synchronized (lock) {

                    if(!flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    log.info("{}", num--);
                    flag = !flag;
                    lock.notify();
                }
            }
        });

        Thread t2 = new Thread(() -> {
            while(num>0) {
                synchronized (lock) {
                    if(flag) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    log.info("{}", num--);
                    flag = !flag;
                    lock.notify();
                }
            }
        });

        t1.start();
        t2.start();
    }

}
